﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace DbSharp.Framework.Storage.IO
{
    class XmlElementFileWriter
    {
        public XmlElementFileWriter()
        {
        }

        #region Private methods

        private StringBuilder WriteTo(XElement rootElement)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            var sb = new StringBuilder();
            using (var writer = XmlWriter.Create(sb, settings))
            {
                settings.Indent = true;
                settings.IndentChars = "  ";
                settings.NewLineChars = Environment.NewLine;
                XDocument xdoc = new XDocument(rootElement);
                xdoc.Save(writer);
            }
            return sb;
        }

        #endregion

        #region Public property/methods

        public void SaveToFile(string outputFileName, string text)
        {
            File.WriteAllText(outputFileName, text, Encoding.UTF8);
        }

        public void SaveToFile(string outputFileName, XElement rootElement)
        {
            var sb = WriteTo(rootElement);
            SaveToFile(outputFileName, sb.ToString());
        }

        #endregion
    }
}
